package org.vectrics.recruiter.config;

/**
 * @author Mike Moore
 * @version 1.0
 */
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

import javax.mail.Session;
import javax.servlet.ServletContext;

import org.apache.log4j.Category;
import org.springframework.beans.factory.BeanFactory;
import org.vectrics.SystemException;
import org.vectrics.common.article.Article;
import org.vectrics.common.controller.ConfigAttribute;
import org.vectrics.common.util.FileUtil;
import org.vectrics.common.util.XmlUtil;
import org.vectrics.config.ApplicationConfiguration;
import org.vectrics.config.MailConfiguration;
import org.vectrics.config.MailConfigurationImpl;
import org.vectrics.domain.Domain;
import org.vectrics.provider.CoreServiceLocator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class RecruitConfig extends ApplicationConfiguration {
    public static int DESCENDING = 0;
    public static int ASCENDING = 1;

    public static final String APPLICATION_DIRECTORY_NAME = "flashrecruit";
    public static final String BUSINESS_RECRUITER = "recruiter";
    public static final String BUSINESS_EMPLOYER = "employer";
    public static final String SURROGATE_KEY_EMAIL_RESUME_ATTCH_FILE = "email.resume.attach.file";
    private String version = null;
    private String buildSite = null;
    private static Category log = Category.getInstance(RecruitConfig.class);
    private static RecruitConfig recruitInstance = null;
    //private String serverIp = "localhost";
    private String templateName = "default";
    private String clientContentPath = "/recruit/custom/client";
    private String articleContentPath = "/recruit/custom/article";
    private Vector hiddenContactAttributes = new Vector();
    private Element menuConfigElement = null;
    private Element formsConfigElement = null;
    private Properties configProperties = new Properties();
    private Vector featuredArticles = new Vector();
    private Vector articles = new Vector();
    private boolean skillsEnabled = false;
    private NotificationsConfig notificationsConfig = new NotificationsConfig();
	private boolean usesEjb = false;
	private boolean usePjaGraphics = false;
	private String pjaFontDirectory = "/usr/local/fonts";
	private boolean buildIndexOnJobUpdate = false;
	private String indexHtmlFileName = null;
	private Properties resources = null;
	private ServletContext servletContext = null;
    private boolean showJobEditCombo = true;
    private String publicSiteContext = null;
	private Collection menus = new HashSet();
	private BeanFactory beanFactory = null;
    private String testDatabaseUrl = "jdbc:mysql://localhost/vectrics";
    private Map<String, String> hibernateProperties = new HashMap<String, String>();
    private Map<String, String> schedulersProperties = new HashMap<String, String>();
	
	/**
	 * @return the hibernateProperties
	 */
	public Map<String, String> getHibernateProperties() {
		return hibernateProperties;
	}

	/**
	 * @param hibernateProperties the hibernateProperties to set
	 */
	public void setHibernateProperties(Map<String, String> hibernateProperties) {
		this.hibernateProperties = hibernateProperties;
	}

	public static String APP_RESOURCE_FILE_NAME = "/WEB-INF/classes/ApplicationResources.properties";
	

    public RecruitConfig() {
    	super();
    	//ConfigurationFactory.setMailConfiguration(this);
    	recruitInstance = this;
    }

    @Override
    public String getWorkflowDataSourceJndi() {
		return CoreServiceLocator.getSystemService().findGlobalSystemConstant("workflow.db.jndi").getValue();
    }

    @Override
    public String getApplicationDirectoryName() {
    	return(APPLICATION_DIRECTORY_NAME);
    }
    
    @Override
    public String getTestDatabaseUrl() {
		return testDatabaseUrl;
	}

	public void setTestDatabaseUrl(String testDatabaseUrl) {
		this.testDatabaseUrl = testDatabaseUrl;
	}

	public void loadDatabaseResources() {
    }

	/**
	 * @return Returns the demoVersion.
	 */
	public boolean getDemoVersion() {
		return CoreServiceLocator.getSystemService().findGlobalSystemConstant("demo").getBooleanValue().booleanValue();
	}

    
    /**
	 * @return Returns the beanFactory.
	 */
	public BeanFactory getBeanFactory() {
		return beanFactory;
	}

	/**
	 * @param beanFactory The beanFactory to set.
	 */
	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

	public void checkForConflicts(Domain domain) {
    	if ((getAllowPasswordEmail(domain)) && (getEmailMustBeUnique(domain) == false)) {
    		log.warn("System allows email but does not assert that email address is unique.");
    	}
    }

	
	public String findBuildProperties(ServletContext servletContext) {
		this.version = "Not Found";
		try {
			InputStream input = servletContext.getResourceAsStream("/WEB-INF/flashrecruit-build.properties");
			Properties buildProperties = new Properties();
			buildProperties.load(input);
			this.version = buildProperties.getProperty("flash.version");
			this.buildSite = buildProperties.getProperty("site");
			input.close();
		} catch (Exception ex) {
			throw new SystemException("Exception reading build properties");
		}
		return(this.version);
	}
	
    public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public String getBuildSite() {
		return buildSite;
	}

	public void setBuildSite(String buildSite) {
		this.buildSite = buildSite;
	}

	public boolean getEnforceCompanyScope() {
		return CoreServiceLocator.getSystemService().findGlobalSystemConstant("security.enforce.company.scope").getBooleanValue().booleanValue();
    }
    
    public boolean getAllowMultipleCompanies(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "allow.multiple.companies").getBooleanValue().booleanValue();
    }
    
	public boolean getCandidateUserNameIsEmail(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "security.candidate.user.is.pwd").getBooleanValue().booleanValue();
	}

	public boolean getModuleCandidatePublicSite(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "module.public.site.candidate").getBooleanValue().booleanValue();
	}

	public boolean getModuleCandidateApply(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "module.candidate.apply").getBooleanValue().booleanValue();
	}

	public String getCandidateDocumentPath(Domain domain) {
		String path = null;
		try {
			path = this.getData();
			path += "/candidate-documents/domain-" + domain.getId();
		} catch (Exception ex) {
			log.error("Exception finding global system constant for document path" , ex);
			throw new SystemException("Exception finding global system constant for document path" , ex);
		}
		return(path);
	}
	
    public String getCandidateDocumentIndexPath(Domain domain) {
		String path = this.getData();
		path += "/cand-doc-index/domain-" + domain.getId();
		FileUtil.createDirectoryIfNotExist(path);
		return(path);
    }
    
	public long getResumeScanMinCount(Domain domain) {
		return CoreServiceLocator.getSystemService().getLongSystemConstant("resume.scan.min.count", domain).longValue();
	}

	public String getEmailedResumeAttachmentFileDirectory(Domain domain) {
    	String directory = this.getApplicationDataDirectory();
    	directory += "/email-attachment/domain-" + domain.getId();
    	return(directory);
    }

	public String getJobReferenceIdPrefix(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "job.auto.ref.id.prefix").getValue();
	}
		
	public boolean getAnswerQuestionForEmailPassword(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "security.pwd.email.rqr.quest").getBooleanValue().booleanValue();
	}
	
    public String getCompanyName(Domain domain) {
    	domain = CoreServiceLocator.getSystemService().findDomain(domain.getId());
		return domain.getPrimaryCompany().getName();
    }
    
    public boolean getHostingModuleInstalled() {
		return CoreServiceLocator.getSystemService().findGlobalSystemConstant("module.hosting").getBooleanValue().booleanValue();
    }

    public boolean getRecruitManagerHasAllJobsAsMyJobs(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "recruit.mgr.has.all.as.my.jobs").getBooleanValue().booleanValue();
    }
    
    public boolean getAllowJobAgents(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "module.job.agent").getBooleanValue().booleanValue();
    }

    public boolean getAllActiveJobsAppearOnRecruitManagerList(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "recruit.mgr.has.all.active.jobs").getBooleanValue().booleanValue();
    }

    public Long getDefaultJobLocation(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "job.default.location").getLongValue();
    }
    
    
    /**
     * Recupera la id location por default para la persona.
     * @param domain
     * @return id location
     */
    public Long getDefaultPersonLocation(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "person.default.location").getLongValue();
    }
    
    public boolean getAllowApplications(Domain domain) {
    	if (getAllowPublicResumeSubmit(domain))
    		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "module.public.application").getBooleanValue().booleanValue();
    	else 
    		return false;
    }

    public boolean getAllowPublicResumeSubmit(Domain domain) {
		return CoreServiceLocator.getSystemService().getBooleanSystemConstant("module.public.resume", domain).booleanValue();
    }

    public String getResumeRecipientEmailAddress(Domain domain) {
		return CoreServiceLocator.getSystemService().getStringSystemConstant("resume.recipient.email.addr", 
				domain);
    }
	
    public String getResumeRecipientEmailHost(Domain domain) {
		return CoreServiceLocator.getSystemService().getStringSystemConstant("resume.recipient.email.host", 
				domain);
    }
	
    public String getResumeRecipientEmailPassword(Domain domain) {
		return CoreServiceLocator.getSystemService().getStringSystemConstant("resume.recipient.email.password", domain);
    }
    
    
	/**
	 * @return Returns the resumeScanMaxCount.
	 */
	public long getResumeScanMaxCount(Domain domain) {
		return CoreServiceLocator.getSystemService().getLongSystemConstant("resume.scan.max.count", domain).longValue();
	}
	public long getResumeScanMinPercentCutoff(Domain domain) {
		return CoreServiceLocator.getSystemService().getLongSystemConstant("resume.scan.min.percent.cutoff", domain).longValue();
	}
    public long getResumeExpireDays(Domain domain) {
		return CoreServiceLocator.getSystemService().getLongSystemConstant("resume.expire.days", domain).longValue();
    }
        
    
    public boolean getShowVectricsLogoOnReports(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "report.show.vectrics.logo").getBooleanValue().booleanValue();
    }

    public boolean getAutoJobReferenceId(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "job.auto.ref.id").getBooleanValue().booleanValue();
    }
    
    public boolean getShowJobListCompanyName(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "job.posting.list.show.company.name").getBooleanValue().booleanValue();
	}

    public boolean getShowJobListCompanyCode(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "job.posting.list.show.company.ref.id").getBooleanValue().booleanValue();
    }
    
    public boolean getShowJobListIcon(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "job.posting.list.show.icon").getBooleanValue().booleanValue();
    }

    public boolean getShowCompactJobListCompanyCode(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "job.posting.compact.list.show.company.ref.id").getBooleanValue().booleanValue();
    }
    public boolean getShowCompactJobListIcon(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "job.posting.compact.list.show.icon").getBooleanValue().booleanValue();
    }
    
    public boolean getShowJobListReferenceCode(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "job.posting.list.show.ref.code").getBooleanValue().booleanValue();
    }
    
    public boolean getShowCompactJobListReferenceCode(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "job.posting.compact.list.show.ref.id").getBooleanValue().booleanValue();
    }

    
	/**
	 * @return Returns the showCompanyOnPublicJobView.
	 */
	public boolean getShowCompanyOnPublicJobView(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "pub.job.list.show.company").getBooleanValue().booleanValue();
	}
    
    public String getPublicSiteContext() {
    	return(publicSiteContext);
    }
    
    public String getPhrase(String keyCode) {
    	String phrase = null;
    	if (resources == null) {
    		loadApplicationResources(servletContext);
    	}
    	phrase = resources.getProperty(keyCode);
    	return(phrase);
    }
    
    @Override
    public Collection getAllMenus() {
    	return(menus);
    }
    
    
    public boolean getShowJobApplicationOnPublicSite(Domain domain) {
    	boolean result = false;
    	if (this.getModuleCandidatePublicSite(domain)) {
    		if (this.getModuleCandidateApply(domain)) { 
    			result = true;
    		}
    	}
    	return(result);
    }

    private void loadApplicationResources(ServletContext context) {
    	log.debug("load() called");
    	
    	try {
    		if (APP_RESOURCE_FILE_NAME == null) {
    			log.error("Application Resources File not specified");
    		}
    		else {
    			resources = new Properties();
    			InputStream input = null;
	    		input = context.getResourceAsStream(APP_RESOURCE_FILE_NAME);
	    		if (input == null) {
	    			log.error("Could not load: " + APP_RESOURCE_FILE_NAME);
	    		}
	    		else {
	    			
	    			try {
	    				String task = "key";
	    				String key = "";
	    				String phrase = "";
	    				int c;
	    				do {
	    					c = input.read();
	    					if (c != -1) {
	    						char ch = (char)c;
	    						if ((ch == '\r') || (ch == '\n')) {
	    							if (task.equals("phrase")) {
	    								log.debug("resource: " + key + " = " + phrase);
	    								resources.setProperty(key, phrase);
	    							}
	    							task = "finding-start";
	    						}
	    						else if (task.equals("finding-start")) {
	    							task = "key";
	    						}
	    						
	    						if (ch == '=') {
	    							task = "phrase";
	    						}
	    						else {
		    							
		    						if (task.equals("key")) {
		    							key += ch;
		    						}
		    						else if (task.equals("phrase")) {
		    							phrase += ch;
		    						}
	    						}
	    					}
	    				} while (c != -1);
	
	    				input.close();
	    			}
	    			catch (Exception ex) {
	    				log.error("Exception loading: " + getFileName(), ex);
	    			}
	    		}
    		}
    	}
    	catch (Exception ex) {
    		log.info("Exception occurred trying to load resources file.  File = "
    				+ getFileName() + "  Exception: " + ex.getMessage());
    	}
    }
    

    @Override
    public MailConfiguration getFromMailConfiguration(Domain domain) {
    	MailConfigurationImpl mailConfig = new MailConfigurationImpl(domain);
		mailConfig.setMailHost(this.getMailHost());
		mailConfig.setMailUserName(this.getMailUserName());
		mailConfig.setMailPassword(this.getMailPassword());
    	
    	return(mailConfig);
    }
    
    public String getTemplateName() {
        return(templateName);
    }
    
    public boolean getSkillsEnabled() {
        return(skillsEnabled);
    }
    
    public Properties getProperties() {
        return(configProperties);
    }

    public String getProperty(String name) {
        log.debug("getProperty() called");
        return(configProperties.getProperty(name));
    }
    
    public void setTemplateName(String name) {
        templateName = name;
    }
    
    public Vector getHiddenContactAttributes() {
        return(hiddenContactAttributes);
        
    }

    //  Read the XML configuratio file's elements into this class' variables.
    @Override
	protected void load(Document document) {
		
	   log.debug("load() - called");
	   Element mainSection = document.getDocumentElement();
	   if (mainSection != null) {
			log.debug("load() - found main xml section");
			loadProperties(mainSection);
			loadDatabaseConfig(mainSection);
			loadReporting(mainSection);
			loadWebConfig(mainSection);
			loadSiteConfig(mainSection);
			loadContactConfig(mainSection);
			loadModules(mainSection);
			loadNotificationConfig(mainSection);
			loadScheduler(mainSection);
		}
		else {
			log.warn("load() - could not find main section of config file.");
		}
	}



    public Collection getFeaturedArticles() {
        return(featuredArticles);
    }

    public Collection getArticles() {
        return(articles);
    }

    public ConfigAttribute findHiddenContactAttribute(String code) {
        ConfigAttribute found = null;
        Iterator iter = getHiddenContactAttributes().iterator();
        while ((found == null) && (iter.hasNext())) {
            ConfigAttribute attr = (ConfigAttribute)iter.next();
            if (attr.getCode().equals(code)) {
                found = attr;
            }
        }
        return(found);
    }

    public Element getFormsConfigElement() {
        return(formsConfigElement);
    }
    
    public Element getMenuConfigElement() {
        return(menuConfigElement);
    }
    
    
    
    
    public String getArticleContentPath() {
        return(articleContentPath);
    }
    
    
    public String getClientContentPath() {
        return(clientContentPath);
    }
    
    static public RecruitConfig getRecruitInstance()  {
        if (recruitInstance == null) {
        	try {
        		throw new SystemException("RecruitConfig not loaded, should be instantiated from Servlet");
        	}
        	catch (Exception ex) {
        		log.error("Exception, RecruitConfig not initialized before requesting static instance");
        	}
        }
        return(recruitInstance);
    }

    
    protected void loadSiteConfig(Element mainSection) {
        String templName = mainSection.getAttribute("template-name");
        setTemplateName(templName);
        
    }

    
    
    protected void loadContactHiddenAttributes(Element contactConfigElement) {
        hiddenContactAttributes.clear();
        NodeList children = contactConfigElement.getElementsByTagName("hidden-attributes");
        if (children.getLength() > 0) {
            log.debug("loadSupportConfig() - company element found.");
            Element hiddenElement = (Element)children.item(0);
            children = hiddenElement.getElementsByTagName("attribute");

            for (int i = 0; i < children.getLength(); i++) {
                Element attrElement = (Element)children.item(i);
                ConfigAttribute attr = new ConfigAttribute();
                attr.setCode(attrElement.getAttribute("code"));
                attr.setName(attrElement.getAttribute("name"));

                if (attr.getCode() == null) 
                    log.error("Error reading recruiter configuration: hidden contact attribute needs 'code'");
                if (attr.getName() == null) 
                    log.error("Error reading recruiter configuration: hidden contact attribute needs 'name'");
                if ((attr.getCode() != null) && (attr.getName() != null)) {
                    log.debug("Adding hidden contact attribute: " + attr.getCode());
                    hiddenContactAttributes.add(attr);
                }
            }
        }
        else
            log.debug("loadContactHiddenAttributes() - no contact hidden attributes.");
    }
	
	protected void loadDatabaseConfig(Element mainSection) {
		NodeList children = mainSection.getElementsByTagName("database");
		if (children.getLength() > 0) {
			log.debug("loadDatabaseConfig() - company element found.");
			Element dbElement = (Element)children.item(0);
			NodeList jdbcChildren = mainSection.getElementsByTagName("jdbc-driver");
			Element jdbcElement = (Element)jdbcChildren.item(0);
			this.setJdbcDriver(jdbcElement.getAttribute("value"));

			NodeList dialectChildren = mainSection.getElementsByTagName("hibernate-dialect");
			Element dialectElement = (Element)dialectChildren.item(0);
			this.setHibernateDialect(dialectElement.getAttribute("value"));
					
			NodeList hibernateChildren = mainSection.getElementsByTagName("hibernate-properties");
			if (hibernateChildren.getLength() > 0) {
				Element elementHibernate = (Element)hibernateChildren.item(0);
				NodeList hibernatePropertiesChildren = elementHibernate.getElementsByTagName("property");	
				for (int i = 0; i < hibernatePropertiesChildren.getLength(); i++) {
					Element element = (Element)hibernatePropertiesChildren.item(i);
					this.getHibernateProperties().put(element.getAttribute("name"), element.getAttribute("value"));
				}
			}
							
			if (this.getHibernateDialect() == null)
				throw new SystemException("Could not find Hibernate Dialect in configuration");
			if (this.getJdbcDriver() == null)
				throw new SystemException("Could not find JDBC Driver in configuration");
		}
		else {
		    throw new SystemException("Could not find 'database' tag as child of root tag");
		}
	}
    
    protected void loadContactConfig(Element mainSection) {
        hiddenContactAttributes.clear();
        NodeList children = mainSection.getElementsByTagName("contact-config");
        if (children.getLength() > 0) {
            log.debug("loadSupportConfig() - company element found.");
            Element configElement = (Element)children.item(0);
            loadContactHiddenAttributes(configElement);
        }
        else
            log.debug("loadSupportConfig() - no support company information found in configuration file.");
    }
    
    protected void loadArticles(Element articleListElement) {
        NodeList children = articleListElement.getElementsByTagName("article");
        for (int i = 0; i < children.getLength(); i++) {
            log.debug("loadArticle() - company element found.");
            Element articleElement = (Element)children.item(i);
            Article article = new Article();
            article.setTitle(articleElement.getAttribute("title"));
            article.setUrl(articleElement.getAttribute("url"));
            String featured = articleElement.getAttribute("featured");
            
            if (featured.startsWith("true")) {
                article.setFeatured(true);
            }
            else 
                article.setFeatured(false);
                
            article.setAbstract(XmlUtil.getChildElementAttribute(articleElement, "abstract"));
            
            
            if (article.getFeatured())
                featuredArticles.add(article);
            
            articles.add(article);
        }
        
    }

	protected void loadNotificationConfig(Element mainElement) {
		NodeList children = mainElement.getElementsByTagName("notifications");
		for (int i = 0; i < children.getLength(); i++) {
			log.debug("loadModule() - notifications element found.");
			Element notificationElement = (Element)children.item(i);
			notificationsConfig.loadConfig(notificationElement);
		}
	}
    
	protected void loadModules(Element mainElement) {
		NodeList children = mainElement.getElementsByTagName("module");
		for (int i = 0; i < children.getLength(); i++) {
			log.debug("loadModule() - module element found.");
			Element moduleElement = (Element)children.item(i);
			String moduleName = moduleElement.getAttribute("name");
            
			if (moduleName.equals("skills")) {
				log.info("MODULE - Skills found");
				skillsEnabled = true;
				log.info("MODULE - Skill Config will lazy load on demand");
			}
            
			if (moduleName.equals("job-posting")) {
				log.info("MODULE - Job Posting");
				findIndexBuildConfig(moduleElement);
				findJobEditConfig(moduleElement);
			}
		}
	}

	
	private void findJobEditConfig(Element moduleElement) {
		NodeList children = moduleElement.getElementsByTagName("job-edit");
		if (children.getLength() > 0) {
			log.debug("loadModule() - 'job-edit' module element found.");
			Element element = (Element)children.item(0);
			findJobEditCompanySelectConfig(element);
		}
	}
	
	
	private void findJobEditCompanySelectConfig(Element moduleElement) {
		NodeList children = moduleElement.getElementsByTagName("company-select");
		if (children.getLength() > 0) {
			log.debug("loadModule() - 'company-select' module element found.");
			Element element = (Element)children.item(0);
			String showComboAttr = element.getAttribute("show-combo");
			if (showComboAttr != null) {
			    if (showComboAttr.startsWith("tr")) {
			        showJobEditCombo = true;
			    } else {
			        showJobEditCombo = false;
			    }
			}
		}
	}

	public boolean getShowJobEditCombo() {
	    return(showJobEditCombo);
	}
	
	private void findIndexBuildConfig(Element moduleElement) {
		NodeList children = moduleElement.getElementsByTagName("index-update");
		for (int i = 0; i < children.getLength(); i++) {
			log.debug("loadModule() - module element found.");
			Element element = (Element)children.item(i);

			String enabled = element.getAttribute("enabled");
			if ((enabled != null) && (enabled.toLowerCase().startsWith("t"))) {
				this.buildIndexOnJobUpdate = true;
				this.indexHtmlFileName = element.getAttribute("index-file");
				log.info("SERVICE ENABLED > AUTO INDEX FILE ON JOB UPDATE - File = " + this.indexHtmlFileName);
			}
			else {
				this.buildIndexOnJobUpdate = false;
				log.info("SERVICE DISABLED > AUTO INDEX FILE ON JOB UPDATE");
			}
		}
		
	}

    
    protected void loadWebConfig(Element mainSection) {
    	log.debug("loadWebConfig() - loading configuration information for web interface elements");
        skillsEnabled = false; 
        hiddenContactAttributes.clear();
        NodeList children = mainSection.getElementsByTagName("web");
        if (children.getLength() > 0) {
            log.debug("loadWebConfig() - 'web' element found.");
            Element configElement = (Element)children.item(0);
            
            
            NodeList clientChildren = configElement.getElementsByTagName("client-content-path");
            if (clientChildren.getLength() > 0) {
                Element clientConfigElement = (Element)clientChildren.item(0);
                clientContentPath = clientConfigElement.getAttribute("path");
                log.debug("loadWebConfig() Load configuration - Client Content Path = " 
                		+ clientContentPath);
            }
            
            
            NodeList articleChildren = configElement.getElementsByTagName("articles");
            if (articleChildren.getLength() > 0) {
                log.debug("loadWebConfig() Load configuration - Articles section found.");
                Element articleElement = (Element)articleChildren.item(0);
                loadArticles(articleElement);
            }
            
            
            clientChildren = configElement.getElementsByTagName("article-content-path");
            if (clientChildren.getLength() > 0) {
                Element clientConfigElement = (Element)clientChildren.item(0);
                articleContentPath = clientConfigElement.getAttribute("path");
                log.debug("loadWebConfig() - Load configuration - Article Content Path = " + articleContentPath);
            }
            
            
            clientChildren = configElement.getElementsByTagName("forms");
            if (clientChildren.getLength() > 0) {
                configElement = (Element)clientChildren.item(0);
                formsConfigElement = configElement;
                log.debug("loadWebConfig() - Load configuration - Found Forms Config");
            }
            else {
                log.debug("loadWebConfig() - Load Configuration - No Forms configuration found.");
            }
        }
        else
            log.debug("loadWebConfig() -  no support company information found in configuration file.");
    }


    protected void loadProperties(Element mainSection) {
        NodeList children = mainSection.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            
            Node child = children.item(i);
            if ((child.getNodeType() == Node.ELEMENT_NODE) && (child.getNodeName().equals("property"))) {
                Element element = (Element)child;
                String name = element.getAttribute("name");
                String value = element.getAttribute("value");
                if ((name != null) && (value != null)) {
                    log.debug("Config - Property = " + name + "  Value = " + value);
                    configProperties.setProperty(name, value);
                }
            }
        }
    }

    protected void loadScheduler(Element mainElement) {
    	NodeList childrenSchedulers = mainElement.getElementsByTagName("schedulers");
    	if (childrenSchedulers.getLength()>0) {
    		Element elementSchedulers = (Element)childrenSchedulers.item(0);
    		NodeList childrenScheduler = elementSchedulers.getElementsByTagName("scheduler");
    		for (int i = 0; i < childrenScheduler.getLength(); i++) {
    			log.debug("loadModule() - notifications element found.");
    			Element elementScheduler = (Element)childrenScheduler.item(i);
    			this.getSchedulersProperties().put(elementScheduler.getAttribute("name"), elementScheduler.getAttribute("value"));
    		}
    	}
    }
    
	protected void loadReporting(Element mainSection) {
		log.debug("loadReporting() - called");
		NodeList children = mainSection.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
            
			Node child = children.item(i);
			if ((child.getNodeType() == Node.ELEMENT_NODE) && (child.getNodeName().equals("reporting"))) {
				Element element = (Element)child;
				
				NodeList reportingChildren = element.getChildNodes();
				for (int j = 0; j < reportingChildren.getLength(); j++) {
					log.debug("loadReporting() - found reporting element");
					Node rptChild = reportingChildren.item(j);
					if ((rptChild.getNodeType() == Node.ELEMENT_NODE) && (rptChild.getNodeName().equals("database"))) {
						log.debug("loadReporting() - getting database properties...");
						Element rptElement = (Element)child;
						//String dataSource = rptElement.getAttribute("datasource");
						//log.debug("dataSource = " + dataSource);
						//this.setDataSourceJndi(dataSource);
					}
				}
			}
		}
	}
	

	/**
	 * @return
	 */
	public String getDataSourceJndi() {
		//return "java:/VectricsDb";
		return "java:comp/env/jdbc/VectricsDb";
	}

	public String getMailHost() {
		return CoreServiceLocator.getSystemService().getStringSystemConstant("mail.host", CoreServiceLocator.getSystemService().findSystemDomain());
	}

	public String getMailPassword() {
		return CoreServiceLocator.getSystemService().getStringSystemConstant("mail.password", CoreServiceLocator.getSystemService().findSystemDomain());
	}

	public String getMailUserName() {
		return CoreServiceLocator.getSystemService().getStringSystemConstant("mail.user", CoreServiceLocator.getSystemService().findSystemDomain());
	}

	public String getMailFromAddress(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "mail.from.address").getValue();
	}

	public String getMailFromName(Domain domain) {
		return CoreServiceLocator.getSystemService().findSystemConstant(domain, "mail.from.name").getValue();
	}
	
	public String getEmailedResumeStoreType(Domain domain) {
		return CoreServiceLocator.getSystemService().getStringSystemConstant("resume.recipient.email.store.type", 
				domain);
	}

//	public void setMailFromName(String mailFromName) {
		//this.mailFromName = mailFromName;
//	}

	/**
	 * @return
	 */
	public String getPjaFontDirectory() {
		return pjaFontDirectory;
	}

	/**
	 * @param pjaFontDirectory
	 */
	public void setPjaFontDirectory(String pjaFontDirectory) {
		this.pjaFontDirectory = pjaFontDirectory;
	}

	/**
	 * @return
	 */
	public boolean getUsePjaGraphics() {
		return usePjaGraphics;
	}

	/**
	 * @param usePjaGraphics
	 */
	public void setUsePjaGraphics(boolean usePjaGraphics) {
		this.usePjaGraphics = usePjaGraphics;
	}

	/**
	 * @return
	 */
	public NotificationsConfig getBroadcastConfig() {
		return notificationsConfig;
	}

	/**
	 * @return
	 */
	public NotificationsConfig getNotificationsConfig() {
		return notificationsConfig;
	}
	
	/**
	 * @return
	 */
	public boolean getBuildIndexOnJobUpdate() {
		return buildIndexOnJobUpdate;
	}

	/**
	 * @param buildIndexOnJobUpdate
	 */
	public void setBuildIndexOnJobUpdate(boolean buildIndexOnJobUpdate) {
		this.buildIndexOnJobUpdate = buildIndexOnJobUpdate;
	}

	/**
	 * @return The file name and path of the index file that will be updated when a job changes.
	 */
	public String getIndexHtmlFileName() {
		return indexHtmlFileName;
	}

	/**
	 * @param indexHtmlFileName
	 */
	public void setIndexHtmlFileName(String indexHtmlFileName) {
		this.indexHtmlFileName = indexHtmlFileName;
	}

	/**
	 * @return Returns true if this web layer will access EJB's for data persistence.
	 */
	public boolean getUsesEjb() {
		return usesEjb;
	}

	/**
	 * @param usesEjb The usesEjb to set.
	 */
	public void setUsesEjb(boolean usesEjb) {
		this.usesEjb = usesEjb;
	}
	
	/*
	 * Returns mail session with configur
	 */
	public Session getMailSession() {
		Session session = null;
		Properties properties = new Properties();

		properties.put("mail.host", RecruitConfig.getRecruitInstance().getMailHost());
		properties.put("mail.password", RecruitConfig.getRecruitInstance().getMailPassword());
		properties.put("mail.smtp.host", RecruitConfig.getRecruitInstance().getMailHost());
		properties.put("mail.smtp.password", RecruitConfig.getRecruitInstance().getMailPassword());
		
		session = Session.getInstance(properties);
		
		return(session);	
	}

	/**
	 * Is calendar functionality enabled.
	 * @return True if calendar enabled.
	 */
	public boolean getCalendarEnabled() {
		return CoreServiceLocator.getSystemService().findGlobalSystemConstant("calendar.module.enabled").getBooleanValue().booleanValue();
	}

	/**
	 * @return the schedulersProperties
	 */
	public Map<String, String> getSchedulersProperties() {
		return schedulersProperties;
	}
    /**
     * retorna si existe y es true el Scheduler en el xml de propiedades.
     * @param schedulerKey
     * @return si existe y es true el Scheduler en el xml de propiedades.
     */
	public boolean isSchedulerEnabled(String schedulerKey) {
		return ((this.getSchedulersProperties().get(schedulerKey) != null) 
				&& (this.getSchedulersProperties().get(schedulerKey).equalsIgnoreCase("true")));
	}


}